//index.js
//获取应用实例
const app = getApp()
var mqtt = require("../../utils/mqtt.js")
var {
  Client,
  Message
} = require('../../utils/paho-mqtt.js')
Page({
  data: {
    client: null, // mqtt连接客户端对象
    clientSubscribe: // mqtt订阅主题
    [
      {
        filter:"17740171896",
        options:{
          qos:1
        }
      }
    ], 
    timerSubscribe: null,
    barcode: '',
    motto: '欢迎使用',
    tip: '请添加设备',
    telephone: "17740171896",
    userInfo: {},
    hasUserInfo: false,
    bluetoothScans:"无",
    equs: [{
        id: "1",
        number: "XJS01",
        position: "地中间",
        cid: "53010000",
        lora_addr: "ff0012",
        name: "4G终端设备",
        status: true,
        alive: true,
      },

      {
        id: "2",
        number: "XJN01",
        position: "第一块地",
        cid: "4e010001",
        lora_addr: "ff0112",
        name: "lora节点1号",
        status: false,
        alive: false,
      },

      {
        id: "3",
        number: "XJN01",
        position: "第二块地",
        cid: "4e010002",
        lora_addr: "ff0212",
        name: "lora节点2号",
        status: true,
        alive: true,
      }
    ],
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  // 打开阀门
  openTap(ev) {
    var id = ev.currentTarget.id;
    var msg = {"tap": 1};
    this.publish(id, JSON.stringify(msg), 0);
    console.log("(publish) topic:" + id + "   msg:" + msg);
  },
  // 关闭阀门
  closeTap(ev) {
    var id = ev.currentTarget.id;
    var msg = { "tap": 0 };
    this.publish(id, JSON.stringify(msg), 0);
    console.log("(publish) topic:" + id + "   msg:" + msg);
  },
  // 扫一扫功能
  scan() {
    // 蓝牙扫描周围模块
    wx.navigateTo({
      url:'../bluetooth/bluetooth'
    })
    //扫一扫功能
    // wx.scanCode({
    //   success: (res) => {
    //     console.log("扫码结果");
    //     console.log(res);
    //     this.setData({
    //       barcode: res.result,
    //       tip: JSON.parse(res.result).id,
    //     })

    //     console.log(this.data.barcode);
    //   },
    //   fail: (res) => {
    //     console.log(res.data);
    //   }
    // })
  },
  // 蓝牙功能
  bluetooth(){
    this.dialog.showDialog()
  },
  //取消事件
  _cancelEvent() {
    console.log('你点击了取消');
    this.dialog.hideDialog();
  },
  //确认事件
  _confirmEvent() {
    console.log('你点击了确定');
    this.dialog.hideDialog();
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  // 订阅主题
  subscribe: function(filter, subscribeOptions) {
    // 订阅
    var client = this.data.client;
    if (client && client.isConnected()) {
      wx.showToast({
        title: '订阅成功'
      })
      return client.subscribe(filter, subscribeOptions);
    }
    
    wx.showToast({
      title: '订阅失败',
      icon: 'none',
      duration: 2000
    })
  },
  doSubscribe: function() {
    // var eqs = this.data.equs
    var subs = this.data.clientSubscribe
    for (var i = 0; i < subs.length;i++){
      this.subscribe(subs[i].filter, subs[i].options);
    }
  },
  publish: function(topic, message, qos = 0, retained = false) {
    // 发布
    var client = this.data.client;
    if (client && client.isConnected()) {
      var message = new Message(message);
      message.destinationName = topic;
      message.qos = qos;
      message.retained = retained;
      wx.showToast({
        title: '发布成功'
      })
      return client.send(message);
    }
    wx.showToast({
      title: '发送失败',
      icon: 'success',
      duration: 2000
    })
  },
  doConnect: function() {
    var that = this;
    if (that.data.client && that.data.client.isConnected()) {
      wx.showToast({
        title: '不要重复连接'
      })
      return
    }
    var client = new Client('wss://15b3t97519.51mypc.cn/mqtt', "test");
    client.onMessageArrived = this.onMessageArrived
    client.onConnectionLost = this.onConnectionLost
    client.connect({
      useSSL: true,
      cleanSession: true,
      keepAliveInterval: 5,
      onSuccess: function() {
        wx.showToast({
          title: '连接服务器成功'
        })
        that.data.client = client
        
      }
    });
  },
  // mqtt消息接收
  onMessageArrived: function(msg) {
    // console.log("onMessageArrived:" + msg.payloadString);
    // client.disconnect();
    var topic = msg.topic
    var pyloadJSON = JSON.parse(msg.payloadString)
    console.log(pyloadJSON)
    var eqs = this.data.equs
    for (var i = 0; i < eqs.length; i++) {
      if (eqs[i].cid === topic) {
        eqs[i].status = pyloadJSON.status
        console.log("接收到mqtt数据")
        this.setData({
          equs: eqs,
        })
        break
      }
    }
  },
  // mqtt连接断开
  onConnectionLost: function(responseObject) {
    if (responseObject.errorCode !== 0)
      console.log("onConnectionLost:" + responseObject.errorMessage);
  },

  /**
 * 生命周期函数--监听页面初次渲染完成
 */
  onReady: function () {
    //获得dialog组件
    this.dialog = this.selectComponent("#dialog");
  },
  /**
 * 生命周期函数--监听页面加载
 */
  onLoad: function () {
    
    var isOk = this.doConnect();
    //console.log(isOk)
    // 连接
    var timerID = setTimeout(this.doSubscribe, 2000);
  },
})